package com.example.jvmsource.config;

import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description: ttranceid过滤器
 *
 * @author zhouyu
 * @create 2020/11/3
 * @since 1.0.0
 */
public class LogTraceInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //traceId初始化
        if (StringUtils.isEmpty(request.getAttribute("traceId"))) {
            MDC.put("traceId", TraceIdUtil.getTraceId());
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove("traceId");
    }

}
